package com.jsn.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jsn.responseEntity.CommonCode;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * AccessDeniedHandler 用来解决认证过的用户访问无权限资源时的异常
 */
public class SmartAccessDeniedHandler
    implements AccessDeniedHandler {
        @Override
        public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException
        accessDeniedException) throws IOException {
            ObjectMapper objectMapper = new ObjectMapper();
            response.setContentType("application/json;charset=UTF-8");
            CommonCode resultEnum = CommonCode.UNAUTHORIZED_ERROR;
            Map map = new HashMap();
            map.put("code", resultEnum.code());
            map.put("msg", resultEnum.message());
            response.setContentType("application/json");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write(objectMapper.writeValueAsString(map));
        }
}
